﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.RemoteEventBus;
using Abp.Runtime.Caching;
using Castle.Core.Logging;
using FwProject.Authorization.Users;
using FwProject.Comm;
using FwProject.Core.Distribution;
using FwProject.Core.Restaurant;
using FwProject.Core.SettlementInfoModel;
using FwProject.Core.TypeNumber;
using FwProject.Distribution;
using FwProject.Distribution.Dto;
using FwProject.JPush.JPushModel;
using FwProject.PublicService.JPush;
using FwProject.Restaurant;
using FwProject.Users;
using Microsoft.EntityFrameworkCore;

namespace FwProject.RemoteEventBus
{

    [RemoteEventHandler(ForType = RemoteTypeHelp.TypeSettlementInfo, ForTopic = RemoteTypeHelp.TopicSettlementInfo)]
    public class SettlementInfoMessage : IRemoteEventHandler, ITransientDependency
    {
        public readonly ICacheManager _catchmanager;
        public readonly IJPushAppservice _jPushAppservice;
        public readonly IUserAppService _userAppService;
        public readonly IRepository<SettlementInfo, Guid> _repositorySettlementInfo;
        public readonly IRepository<RestaurantUserInfo, Guid> _repositoryRestaurantUserInfo;
        private readonly IRepository<DistributionInfo, Guid> _repositoryDistributionInfo;
        public readonly IRepository<TypeNumberInfo, Guid> _repositoryTypeNumberInfo;
        private readonly IRepository<User, long> _userRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public IRemoteEventBus remoteEventBus { get; set; }//缓存对象
        public ILogger logger { get; set; }
        public SettlementInfoMessage(ICacheManager catchmanager, IJPushAppservice jPushAppservice,
                                        IRepository<SettlementInfo, Guid> repositorySettlementInfo,
                                         IUserAppService userAppService,
                                         IRepository<RestaurantUserInfo, Guid> repositoryRestaurantUserInfo,
                                         IRepository<User, long> userRepository,
                                         IRepository<DistributionInfo, Guid> repositoryDistributionInfo,
                                         IRepository<TypeNumberInfo, Guid> repositoryTypeNumberInfo,
                                         IUnitOfWorkManager unitOfWorkManager
                                          )
        {
            _repositoryDistributionInfo = repositoryDistributionInfo;
            _userRepository = userRepository;
            _repositoryRestaurantUserInfo = repositoryRestaurantUserInfo;
            _repositorySettlementInfo = repositorySettlementInfo;
            _catchmanager = catchmanager;
            _jPushAppservice = jPushAppservice;
            _userAppService = userAppService;
            logger = NullLogger.Instance;
            _unitOfWorkManager = unitOfWorkManager;
            _repositoryTypeNumberInfo = repositoryTypeNumberInfo;
            remoteEventBus = NullRemoteEventBus.Instance;

        }
        [UnitOfWork]
        public void HandleEvent(RemoteEventArgs eventArgs)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                try
                {
                    Dictionary<Guid, SeltmentTypeNumberDto> dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<Guid, SeltmentTypeNumberDto>>(eventArgs.EventData.Data[RemoteTypeHelp.ListT].ToString());
                    if (dic != null)
                    {
                        var t = _repositorySettlementInfo.GetAllIncluding(o => o.EmployeeDriverDao, o => o.RestaurantInfoModel);
                        var tdmodel = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails);
                        foreach (var item in dic)
                        {
                            var RestaurantInfoId = Guid.Empty;
                            foreach (var d in item.Value.DisId)
                            {
                                var dmodel = tdmodel.Where(o => o.Id == d).FirstOrDefault();
                                RestaurantInfoId = dmodel.Restaurantid.Value;
                                if (dmodel != null)
                                {
                                    decimal sumPrice = 0;
                                    dmodel.SettlementId = item.Key;
                                    dmodel.Pricestatus = Pricestatus.已制单;
                                    foreach (var details in dmodel.DistributionInfoListDetails)
                                    {
                                        var temType = item.Value.TypeNumber.Where(o => o.TypeNumberId == details.TypeNumberInfoId && o.TypeNumberoldPrice==details.TypeNumberPrice).FirstOrDefault();
                                        if (temType != null && temType.TypeNumberPrice != details.TypeNumberPrice)
                                        {
                                           
                                            var m = _repositoryTypeNumberInfo.Get(temType.TypeNumberId);
                                            details.Sumprice = (m.Count * temType.TypeNumberPrice * (details.Distributioncount - details.Backboxcount) + (details.Backnumbercount + details.Damagecount) * temType.TypeNumberPrice);
                                            details.TypeNumberPrice = temType.TypeNumberPrice;
                                            sumPrice += details.Sumprice;
                                        }
                                        else
                                        {
                                            sumPrice += details.Sumprice;
                                        }
                                        details.PricesId = item.Key;
                                        details.Pricestatus = Pricestatus.已制单;
                                    }
                                    dmodel.TotalPrice = sumPrice;
                                    // _repositoryDistributionInfo.Update(dmodel);
                                }

                            }
                            var model = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser).Where(o => o.RestaurantInfoId == RestaurantInfoId).FirstOrDefault();
                            TypeSettlementPushMessageModel pushModel = new TypeSettlementPushMessageModel();
                            pushModel.TopicModel = JPush.JPushHelpel.TopicRestauran;
                            pushModel.UserId = model.EmployeeRestaurantId;
                            pushModel.Id = item.Key;
                            _jPushAppservice.RestaurantPushMessage(model.EmployeeRestauranUser.Mobile, pushModel, $"配送单位已完成配制单，请立即查看");

                        }
                    }
                    var catcheventDate = new RemoteEventData(RemoteTypeHelp.TypeModelCatch)
                    {
                        Data = { [RemoteTypeHelp.Model] = nameof(DistributionInfo) }
                    };
                    remoteEventBus.Publish(RemoteTypeHelp.TopicSystemCatch, catcheventDate);

                }
                catch (Exception exe)
                {
                    logger.Error($"制单通知{nameof(TypeSettlementPushMessageModel)}失败", exe);
                }
                finally
                {

                    logger.Info($"制单通知{nameof(TypeSettlementPushMessageModel)}");
                }

                unitOfWork.Complete();
            }
        }
    }

}
